import router from "@/router"
import { serverStore } from "@/stores/server"
import axios from "axios"
import { ElMessage } from "element-plus"
import { showWebLoading, closeWebLoading } from '@/utils/LodingUtil'
import { decryptData } from "./CryptoJSUtil"

const { server } = serverStore()

// 创建axios示例
const axiosInstance = axios.create({
    baseURL: server,
    timeout: 20000,
    headers: {
        'Content-Type': 'application/json'
    }
})

// 请求拦截器
axiosInstance.interceptors.request.use(
    (config) => {
        const loading = showWebLoading()
        config.webLoading = loading
        // 携带token
        const token = localStorage.getItem('token')
        if (token) {
            config.headers.token = token
        }
        return config
    },
    (error) => {
        return Promise.reject(error)
    }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
    (res) => {
        const loading = res.config.webLoading
        if (loading) {
            closeWebLoading(loading)
        }
        if (res.data && typeof res.data === "string") {
            try {
                const decrypted = decryptData(res.data)
                res.data = JSON.parse(decrypted)
            } catch (err) {
                console.error('解密响应失败:', err);
            }
        }
        if (res.data.code === 0) {
            ElMessage.error(res.data.msg)
        }
        if (res.data.code === 1) {
            if (res.data.msg !== null) {
                ElMessage.success(res.data.msg)
            }
            return res.data
        }
        if (res.data.code === 401) {
            ElMessage.error(error.response.msg)
            return
        }
        return Promise.reject(res.data);
    },
    (error) => {
        const loading = error.config.webLoading
        if (loading) {
            closeWebLoading(loading)
        }
        // 错误的特殊情况 => 401 权限不足 或 token 过期 => 拦截到登录
        if (error.response?.status === 401) {
            router.push('/')
        }
        // 错误的默认情况 => 只要给提示
        ElMessage.error('服务异常');
        return Promise.reject(error)
    }
);

export default axiosInstance